package stack;

import java.util.ArrayDeque;
import java.util.Deque;

public class Calculate {
    public static int code(String ss) {
        char[] s = ss.toCharArray();
        char op = '+';
        Deque<Integer> ret = new ArrayDeque<>();
        int tmp = 0;

        for (int i = 0; i < s.length;){
            if (s[i] == ' '){
                i++;
            }else if (s[i] >= '0' && s[i] <= '9'){
                tmp = 0;
                while (i < s.length && s[i] >= '0' && s[i] <= '9'){
                    tmp = tmp * 10 + (s[i] - '0');
                    i++;
                }

                if (op == '+'){
                    ret.push(tmp);
                }else if (op == '-'){
                    ret.push(-tmp);
                }else if (op == '*'){
                    ret.push(ret.pop() * tmp);
                }else {
                    ret.push(ret.pop() / tmp);
                }
            }else {
                op = s[i];
                i++;
            }
        }

        int newRet = 0;
        while (!ret.isEmpty()){
            newRet += ret.pop();
        }

        return newRet;
    }

    public static void main(String[] args) {
        Calculate.code("3+2*2");
    }
}
